package cn.bonoon.kernel.web.components;

import cn.bonoon.kernel.IdGenerator;
import cn.bonoon.kernel.annotations.TransformFile;
import cn.bonoon.kernel.descriptors.UIPropertyAccessor;
import cn.bonoon.kernel.util.StringHelper;
import cn.bonoon.kernel.web.annotations.components.AsFile;
import cn.bonoon.kernel.web.html.UIPropertyBuilder;
import cn.bonoon.kernel.web.html.form.ComponentPropertyParser;

public class FileComponent extends AbstractComponent{
	
	private final AsFile com;
	private final TransformFile transformFile;
	public FileComponent(ComponentPropertyParser property, UIPropertyAccessor accessor, AsFile asFile) {
		super(property, accessor);
		this.com = asFile;
		this.transformFile = accessor.getAnnotation(TransformFile.class);
		this.componentParser.hasFile();
	}

	@Override
	protected void parser(UIPropertyBuilder builder) {
		StringBuilder html = builder.getInitHtml();
		int editorWidth = componentWidth() - 80;
		if (/*cd && sn*/com.download()){
			editorWidth -= 30;
		}
		String pathPropertyName = builder.getBindedName() + '.' + componentName;
		String titlePropertyName = null, fname, dname;
		if(null != transformFile){
			titlePropertyName = transformFile.propertyOriginalName();
			if(!titlePropertyName.isEmpty()){
				titlePropertyName = builder.getBindedName() + '.' + titlePropertyName;
			}
			
			fname = componentName + transformFile.suffixComponent();
			dname = componentName + transformFile.suffixDeletable();
		}else{
			fname = componentName + "-file";
			dname = componentName + "-deleted";
		}
		if(StringHelper.isEmpty(titlePropertyName)){
			titlePropertyName = pathPropertyName;
		}
		html.append("<input type='file' name='").append(fname).append("' style='width:").append(editorWidth)
			.append("px;' />#if($").append(pathPropertyName).append(" && !$").append(pathPropertyName).append(".empty)");
		String deleteId = IdGenerator.fixed();
		if(com.download()){
			String downloadId = IdGenerator.fixed();//"dl-" + componentId;
			html.append("<a target='_blank' href='#springUrl($").append(pathPropertyName).append(")' id='").append(downloadId).append("' title='$!{");
			html.append(titlePropertyName).append("}'>文件</a> | ");
			StringBuilder js = builder.getInitBlock();
			js.append("jQuery('#").append(deleteId).append("').click(function(){jQuery('#").append(downloadId).append("').css('text-decoration', this.checked ? 'line-through' : 'none');});");
		}
		// 删除附件
		html.append("<input style='vertical-align:middle' id='").append(deleteId).append("' type='checkbox' name='").append(dname);
		html.append("' value='true'/><label for='").append(deleteId).append("' title='删除文件：$!{").append(titlePropertyName).append("}'>删除<label><input");
		__component(html);
		html.append("value='${").append(pathPropertyName).append("}' type='hidden'/>#end ");
	}

}
